package com.example.foodwebbackend.service;

import com.example.foodwebbackend.entity.UserRating;
import com.example.foodwebbackend.mapper.UserRatingMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserRatingService {

    @Autowired
    private UserRatingMapper userRatingMapper;

    /**
     * 分页获取用户评价
     */
    public Map<String, Object> getUserReviews(Integer userId, Integer page, Integer size) {
        int offset = (page - 1) * size;
        List<UserRating> reviews = userRatingMapper.findByUserId(userId, offset, size);
        Integer total = userRatingMapper.countByUserId(userId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("data", reviews);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        
        return result;
    }

    /**
     * 添加评价
     */
    public UserRating addReview(UserRating userRating) {
        // 检查用户是否已经评价过该菜品
        UserRating existingReview = userRatingMapper.findByUserIdAndFoodId(
            userRating.getUserId(), userRating.getFoodId());
        
        if (existingReview != null) {
            throw new RuntimeException("您已经评价过该菜品");
        }
        
        userRating.setRatingTime(LocalDateTime.now());
        userRatingMapper.insert(userRating);
        return userRating;
    }

    /**
     * 更新评价
     */
    public UserRating updateReview(UserRating userRating) {
        userRating.setRatingTime(LocalDateTime.now());
        userRatingMapper.update(userRating);
        return userRating;
    }

    /**
     * 删除评价
     */
    public boolean deleteReview(Integer ratingId) {
        return userRatingMapper.deleteById(ratingId) > 0;
    }

    /**
     * 获取用户对特定菜品的评价
     */
    public UserRating getUserFoodReview(Integer userId, Integer foodId) {
        return userRatingMapper.findByUserIdAndFoodId(userId, foodId);
    }
    
    /**
     * 获取菜品的所有评价
     */
    public List<Map<String, Object>> getFoodReviews(Integer foodId) {
        return userRatingMapper.findFoodReviews(foodId);
    }
} 